<?php

namespace app\site\controller;

use app\common\exception\MiException;
use app\common\service\CommonSiteConfigService;
use app\common\service\pay\WxpayService;
use app\model\site\User;
use app\model\site\UserOauth;
use app\model\store\DistCashApply;
use app\model\store\DistRewardLog;
use app\site\service\DistCashApplyService;
use app\site\service\SiteAuthService;
use think\db\exception\DbException;
use think\facade\Db;
use function checkSiteAuth;
use function request;

class DistCashApplyController extends AController
{
    /**
     * @throws DbException
     * @throws MiException
     */
    public function index() {
        $ser = DistCashApplyService::instance();
        return $this->reqSer->setService($ser)->setPaginate()->getResponse();
    }

    /**
     * @throws MiException
     */
    public function audit(){
        checkSiteAuth('distCashApply/edit');

        if (!request()->isPost()){
            return jsonError(REQUEST_ERROR);
        }

        Db::transaction(function () {
            $id = $this->post('id');
            $status = $this->post('audit');
            if (!$id){
                throw new MiException(PARAM_ERROR);
            }
            // 使用加锁查询
            $info = DistCashApply::where('id', $id)->lock(true)->find();

            if ($info->audit != 0){   // 如果不是未审核
                throw new MiException("请勿重复审核");
            }
            if ($status == 1){  // 同意退款
                $info->audit = 1;

                // 提现到零钱
                $config = CommonSiteConfigService::instance()->getWxPayConfig(SiteAuthService::instance()->getSiteId());
                $cashNo = makeOrderNo('CON');
                $cashAmount = (int)($info->amount * 100);
                $openid = UserOauth::where('user_id', $info->user_id)->where('oauth_type', 'mp-weixin')->value('oauth_id');
                WxpayService::getInstance($config)->transfer([
                    'out_batch_no' => $cashNo,
                    'batch_name' => '分销佣金提现',
                    'batch_remark' => '分销提现',
                    'total_amount' => $cashAmount,
                    'total_num' => 1,
                    'transfer_detail_list' => [
                        [
                            'out_detail_no' => $cashNo,
                            'transfer_amount' => $cashAmount,
                            'transfer_remark' => '佣金提现',
                            'openid' => $openid,
                        ]
                    ]
                ]);

                // 创建佣金明细(提现佣金已经在创建提现申请时扣除)
                DistRewardLog::create([
                    'site_id' => SiteAuthService::instance()->getSiteId(),
                    'user_id' => $info->user_id,
                    'amount' => $info->amount * -1,
                    'reward_type' => 3,
                    'note' => '提现',
                    'status' => 1,
                ]);

            }else{  // 不同意提现，退回佣金
                $note = $this->post('audit_note');
                if (!$note){
                    throw new MiException("没有填写拒绝原因");
                }
                // 将扣除的佣金退回到佣金余额
                User::where('id', $info->user_id)->inc('reward', $info->amount)->update();

                $info->audit_note = $note;
                $info->audit = -1;
            }
            // 保存退款信息
            $info->save();

        });

        return jsonSuccess();
    }
}
